<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page.sync="page"
        :data="tableData"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load="getList"
        @search-change="searchChange"
        @search-reset="form = {marketSn: ''}"
        @refresh-change="refreshChange"
        @row-del="rowDel">

        <template slot-scope="scope" slot="areaSnSearch">
          <el-cascader
            v-model="form.areaSn"
            :options="areaList"
            :change-on-select="true"
            filterable
            size="small"
            class="fill-width"
            clearable
            @change="handleChangeArea"></el-cascader>
        </template>
        <template slot-scope="scope" slot="marketSnSearch">
          <el-select
            :remote-method="remoteMarket"
            v-model="form.marketSn"
            filterable
            clearable
            size="small"
            remote>
            <el-option
              v-for="item in marketList"
              :key="item.marketSn"
              :label="item.marketName"
              :value="item.marketSn"/>
          </el-select>
        </template>

        <template slot-scope="scope" slot="directorIdSearch">
          <el-select
            :remote-method="remoteStaffList"
            v-model="form.directorId"
            filterable
            clearable
            size="small"
            remote
            placeholder="请选择">
            <el-option
              v-for="item in staffList"
              :key="item.id"
              :label="item.name"
              :value="item.id"></el-option>
          </el-select>
        </template>

        <template slot-scope="scope" slot="createDateSearch">
          <el-date-picker
            v-model="form.createTime"
            type="daterange"
            range-separator="至"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </template>

        <template slot-scope="scope" slot="menu">
          <el-button
            icon="el-icon-view"
            type="text"
            size="small"
            @click="goDetail(scope.row)">详情
          </el-button>
          <el-button
            icon="el-icon-edit"
            type="text"
            size="small"
            @click="goEdit(scope.row)">编辑
          </el-button>
        </template>
        <template slot="menuLeft">
          <el-button type="primary" icon="el-icon-plus" size="small" @click="addCustomer">新增客户</el-button>
        </template>
        <template slot="menuLeft">
          <customer_import ref="customerImport" style="display: inline"/>
        </template>
        <template slot="menuLeft">
          <customer_position_import ref="customerPositionImport" style="display: inline"/>
        </template>
        <template slot="menuLeft">
          <customer_linkman_import ref="customerLinkmanImport" style="display: inline"/>
        </template>
        <template slot="menuLeft">
          <customer_address_import ref="customerAddressImport" style="display: inline"/>
        </template>
      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
import { fetchList, delObj } from '@/api/crm/customer'
import { tableOption } from '@/const/crud/crm/customer/customerList'
import { mapGetters } from 'vuex'
import customer_import from '@/components/crm/excel_import/customer_import'
import customer_position_import from '@/components/crm/excel_import/customer_position_import'
import customer_linkman_import from '@/components/crm/excel_import/customer_linkman_import'
import customer_address_import from '@/components/crm/excel_import/customer_address_import'
import { areaTree } from '@/api/crm/area'
import { formatCascader } from '@/const/common/tool'
import { fetchList as marketListApi } from '@/api/crm/marketmanage'
import { fetchList as staffListApi } from '@/api/crm/marketemployee'

export default {
  name: 'index',
  components: {
    customer_import,
    customer_position_import,
    customer_linkman_import,
    customer_address_import
  },
  data() {
    return {
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableOption: tableOption,
      tableData: [],
      tableLoading: false,
      areaList: [],
      marketList: [],
      staffList: [],
      form: {
        marketSn: ''
      }
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.crm_customer_add, false),
        delBtn: this.vaildData(this.permissions.crm_customer_del, false),
        editBtn: this.vaildData(this.permissions.crm_customer_edit, false)
      }
    }
  },
  created() {
    this.getHeight()
    this.getAreaList()
    this.getStaffList()
  },
  methods: {
    getHeight() {
      const tableHeight = Math.max(window.innerHeight - 550, 200)
      this.tableOption.maxHeight = tableHeight + 'px'
    },
    //查询采购单列表
    getList(page, params) {
      this.tableLoading = true
      const query = getQuery(this.form)
      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, query)).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      })
    },
    async remoteStaffList(name) {
      const query = {}
      if (name) query.name = name
      const res = await staffListApi(Object.assign(query, { current: 1, size: 50 }))
      this.staffList = res.data.data.records
    },
    async getStaffList() {
      const res = await staffListApi({ current: 1, size: 100 })
      this.staffList = res.data.data.records
    },
    async getAreaList() {
      const res = await areaTree({ current: 1, size: 100 })
      this.areaList = formatCascader(res.data.data, 'areaName', 'areaSn')
    },
    handleChangeArea(value) {
      this.form.marketSn = ''
      let areaSn = ''
      if (Array.isArray(value) && value.length > 0) areaSn = value[value.length - 1]
      this.getMarketList({ areaSn })
    },
    async remoteMarket(marketName) {
      let areaSn = ''
      const value = this.form.areaSn
      if (Array.isArray(value) && value.length > 0) areaSn = value[value.length - 1]
      const res = await marketListApi({ areaSn, marketName, current: 1, size: 20 })
      this.marketList = res.data.data.records
    },
    async getMarketList(params) {
      const res = await marketListApi(params)
      this.marketList = res.data.data.records
    },
    rowDel: function(row, index) {
      var _this = this
      this.$confirm('是否确认删除' + row.customerName, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delObj(row.customerSn)
      }).then(data => {
        _this.tableData.splice(index, 1)
        _this.$message({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
        this.getList(this.page)
      }).catch(function(err) {
      })
    },
    /**
       * 搜索回调
       */
    searchChange(form, done) {
      this.getList(this.page, form)
      // console.log(form)
      done()
    },
    /**
       * 刷新回调
       */
    refreshChange(info) {
      this.getList(this.page, this.filterForm(info.searchForm))
    },
    addCustomer() {
      this.$router.push({
        path: '/customer/addCustomer'
      })
    },
    handleClick(row) {
      // console.log(row)
    },
    goDetail(row) {
      let query = {
        res: {
          customerSn: row.customerSn
        }
      }
      this.$router.push({ path: '/customer/customerDetail', query: query })
    },
    goEdit(row) {
      let query = {
        res: JSON.stringify(row)
      }
      this.$router.push({
        path: '/customer/editCustomer',
        query: query
      })
    }
  }
}
function getQuery(params) {
  const query = JSON.parse(JSON.stringify(params))
  if (params.createTime && Array.isArray(params.createTime) && params.createTime.length === 2) {
    query.startDate = params.createTime[0]
    query.endDate = params.createTime[1]
  }
  if (params.areaSn && Array.isArray(params.areaSn) && params.areaSn.length > 0) {
    query.areaSn = params.areaSn[params.areaSn.length - 1]
  }
  delete query.createTime
  clean(query)
  return query
}

function clean(obj) {
  for (const propName in obj) {
    if (obj[propName] === null || obj[propName] === '') {
      delete obj[propName]
    }
  }
}
</script>

<style lang="scss" scoped>
.el-range-editor--small.el-input__inner {
    height: 32px !important;
}
</style>
